package com.raisecom.view.custom;

import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;

/**
 * 
 * @author lilz-2686
 *
 */
public class JCheckList<T> extends JList{
	
	private static final long serialVersionUID = -847489620258792818L;
	
	private CheckListItem[] checkListItemData;
	
	public CheckListItem[] getCheckListItemData() {
		return checkListItemData;
	}

	public void setCheckListItemData(CheckListItem[] checkListItemData) {
		this.checkListItemData = checkListItemData;
	}
	
	public JCheckList(CheckListItem[] checkListItemData) {
		super(checkListItemData);
		this.checkListItemData = checkListItemData;
		setCellRenderer(new CheckListRenderer());
		setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		setFixedCellHeight(15);
		addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent event) {
				JList list = (JList) event.getSource();

				int index = list.locationToIndex(event.getPoint());
				
				CheckListItem item = (CheckListItem) list.getModel().getElementAt(index);

				item.setSelected(!item.isSelected());

				Rectangle selectCellBound = list.getCellBounds(index, index);
				
				list.repaint(selectCellBound);
			}
		});
	}

}

// Handles rendering cells in the list using a check box

class CheckListRenderer extends JCheckBox implements ListCellRenderer {
	private static final long serialVersionUID = 2926753490618973146L;

	public Component getListCellRendererComponent(JList list, Object value,
			int index, boolean isSelected, boolean hasFocus) {
		setEnabled(list.isEnabled());
		setSelected(((CheckListItem) value).isSelected());
		setFont(list.getFont());
//		setBackground(list.getBackground());
//		setForeground(list.getForeground());
		setBackground(isSelected ? list.getSelectionBackground() : list
				.getBackground());
		setForeground(isSelected ? list.getSelectionForeground() : list
				.getForeground());
		
		setText(value.toString());
//		setIcon(new ImageIcon("D:\\workspace2\\MysqlSwing\\src\\image\\dialog\\datasynch.png"));
		return this;
	}
}
